/*
 * @Description:
 * @Autor: 万洲
 * @Date: 2022-11-22 16:28:33
 * @LastEditors: 万洲
 * @LastEditTime: 2022-12-07 16:59:26
 */
import BaseTableLayout from "@/components/BaseTableLayout";
import { ElButton, ElTable, ElTableColumn, ElForm, ElFormItem, ElInput, ElCard, ElScrollbar, ElTree, ElSwitch, ElSelect, ElOption, ElDatePicker } from "element-plus";
import { computed, defineComponent, onMounted, reactive, ref, StyleValue, watch } from "vue";
import { Plus, Delete, Edit, Download } from "@element-plus/icons-vue";
import { baseTableConfig } from "@/constants/compontentsConfig";
import RenderDropDownButton from "@/components/RenderDropDownButton";
import { useElPagination } from "@/hooks/useElPagination";
import { reqChangeUserStatus, reqGetDeptTreeSelect, reqGetUserListPage } from "@/api/System";
import { useListNopage } from "@/hooks/useListNopage";
import { ITableSlots } from "@/types/base/ITableSlots";
import { ISystemUserListItem } from "@/types/system/ISystemUserListItem";
import { useDict } from "@/hooks/useDict";
import $$ from "@/utils/wzUtils";
import { IDeptTreeSelectItem } from "@/types/system/IDeptTreeSelectItem";
interface IState {
	searchModel: {
		deptId?: number;
		userName?: string;
		phonenumber?: number;
		status?: number;
		dateRange?: string[];
	};
	visible: boolean;
	leftTreeSearchValue?: string;
}
const aaa = Array.from({ length: 1000 }).map((a) => ({ name: "wz" }));
export default defineComponent({
	setup: (props) => {
		const state = reactive<IState>({
			searchModel: {},
			visible: false
		});
		const tableRef = ref<InstanceType<typeof ElTable>>();
		const treeRef = ref<InstanceType<typeof ElTree>>();
		/** 部门树 */
		const { loadData: loadDeptTreeData, dataSource: deptTreeDatasource } = useListNopage({ apiFunction: reqGetDeptTreeSelect });
		const { loadData: loadTableData, dataSource: tableDatasouce, handleRefresh, Pagination, loadingStatus } = useElPagination({ apiFunction: reqGetUserListPage });
		const { dict } = useDict(["sys_normal_disable"]);
		const realSearchModel = computed(() => $$.formatDateRange(state.searchModel, state.searchModel.dateRange));
		/** 监听更改值手动调用树筛选 */
		watch(
			() => state.leftTreeSearchValue,
			(val) => treeRef.value!.filter(val)
		);
		onMounted(async () => {
			await loadDeptTreeData();
			await loadTableData();
		});
		/**
		 * 部门树选择
		 */
		const handleDeptTreeClick = async (treeData: IDeptTreeSelectItem) => {
			state.searchModel.deptId = treeData.id;
			handleRefresh(realSearchModel.value);
		};
		return () => (
			<div class="appContaierDouble">
				<ElCard class={"fillCardHeightBody"} style={{ minWidth: "240px" } as StyleValue} shadow={"never"} header={"部门列表"}>
					<ElScrollbar>
						<ElInput placeholder="请输入部门名称" v-model={state.leftTreeSearchValue} style={{ marginBottom: "12px" } as StyleValue} />
						<ElTree
							ref={treeRef}
							onNode-click={handleDeptTreeClick}
							data={deptTreeDatasource.value}
							expandOnClickNode={false}
							defaultExpandAll
							filterNodeMethod={(value: string, data) => {
								if (!value) return true;
								return data.label.includes(value);
							}}
							highlight-current
						/>
					</ElScrollbar>
				</ElCard>
				<BaseTableLayout
					onRefresh={handleRefresh}
					defaultSearchVisibel={true}
					tableTitle={"用户管理"}
					v-slots={{
						/** 搜索表单 */
						searchContaier: () => {
							return (
								<>
									<ElForm inline>
										<ElFormItem label="用户昵称">
											<ElInput placeholder="请输入" v-model={state.searchModel.userName} />
										</ElFormItem>
										<ElFormItem label="手机号码">
											<ElInput placeholder="请输入" v-model={state.searchModel.phonenumber} />
										</ElFormItem>
										<ElFormItem label="状态">
											{(() => {
												if (!dict.value.sys_normal_disable) debugger;
												return (
													<ElSelect placeholder="请选择" v-model={state.searchModel.status}>
														{dict.value.sys_normal_disable.map((item) => (
															<ElOption key={item.dictCode} label={item.dictLabel} value={item.dictValue} />
														))}
													</ElSelect>
												);
											})()}
										</ElFormItem>
										<ElFormItem label="创建时间">
											<ElDatePicker type="daterange" rangeSeparator="-" startPlaceholder="开始日期" endPlaceholder="结束日期" v-model={state.searchModel.dateRange} valueFormat="YYYY-MM-DD" />
										</ElFormItem>
										<ElFormItem>
											<ElButton type={"primary"} onClick={() => handleRefresh(realSearchModel.value)}>
												搜索
											</ElButton>
											<ElButton
												onClick={() => {
													state.searchModel = { deptId: state.searchModel.deptId };
													handleRefresh(realSearchModel.value);
												}}>
												重置
											</ElButton>
										</ElFormItem>
									</ElForm>
								</>
							);
						},
						/** 表头按钮组 */
						headerButtons: () => {
							return (
								<>
									<ElButton icon={Plus} type={"primary"} plain onClick={() => (state.visible = true)}>
										新增
									</ElButton>
									<ElButton icon={Edit} type={"success"} plain>
										编辑
									</ElButton>
									<ElButton icon={Delete} type={"danger"} plain>
										删除
									</ElButton>
									<ElButton icon={Download} type={"warning"} plain>
										导出
									</ElButton>
								</>
							);
						},
						/** 表格主体 */
						tableContaier: () => {
							const moreOptions: InstanceType<typeof RenderDropDownButton>["$props"]["options"] = [
								{
									label: "禁用",
									click: async () => {}
								}
							];
							return (
								<ElTable data={tableDatasouce.value} {...baseTableConfig} ref={tableRef} v-loading={loadingStatus.value}>
									<ElTableColumn prop="userId" label="用户编号" />
									<ElTableColumn prop="nickName" label="用户昵称" />
									<ElTableColumn label="部门" v-slots={(scope: ITableSlots<ISystemUserListItem>) => scope.row.dept.deptName} />
									<ElTableColumn prop="phonenumber" label="手机号码" />
									<ElTableColumn
										label="状态"
										v-slots={(scope: ITableSlots<ISystemUserListItem>) => (
											<ElSwitch
												v-model={scope.row.status}
												activeValue={"0"}
												inactiveValue={"1"}
												onChange={async () => {
													loadingStatus.value = true;
													let result = await reqChangeUserStatus({ status: scope.row.status, userId: scope.row.userId });
													loadingStatus.value = false;
													if (result.code !== 200) return (scope.row.status = "1");
												}}
											/>
										)}
									/>
									<ElTableColumn prop="createTime" label="创建时间" />
									<ElTableColumn label="操作" fixed={"right"} width={"210"}>
										<ElButton type={"primary"} size="small">
											编辑
										</ElButton>
										<ElButton type={"danger"} size="small">
											删除
										</ElButton>
										<RenderDropDownButton options={moreOptions} />
									</ElTableColumn>
								</ElTable>
							);
						},
						/** 分页 */
						PaginationContaier: () => <Pagination />
					}}></BaseTableLayout>
			</div>
		);
	}
});
